<template>
  <div class="L-orgRef">
  
    <div class="L-top-bar">
      <form action="/">
        <van-search v-model="keyword" show-action placeholder="请输入搜索关键词" @search="onSearch">
          <template #action>
            <div @click="onSearch">搜索</div>
          </template>
        </van-search>
      </form>
    </div>

    <div class="L-orgTree">
      <van-checkbox-group v-model="selecteddata" ref="checkboxGroup">
        <orgTree :listMode="listMode" :selecteddata="selecteddata" :mode="mode" :bo="bo" :orgData="orgData"
          :handleExpand="handleExpand" :handleChecked="handleChecked"></orgTree>
      </van-checkbox-group>
    </div>

    <van-tabbar safe-area-inset-bottom v-if="mode === 'multiple'">
      <div class="L-orgRef-tabbar">
        <van-button @click="reBack" color="#5891e0" type="primary" style="width:90%">确定</van-button>
      </div>
    </van-tabbar>

  </div>
</template>

<script>
import orgTree from './orgRef/orgTree.vue'
import Vue from 'vue'
import { Toast } from 'vant'
import qs from 'qs'
Vue.use(Toast)

export default {
  name: 'ref',
  components: { orgTree },
  data() {
    return {
      bo: this.$route.params.bo || 'employee',
      orgData: [],
      mode: this.$route.params.mode || 'single',
      keyword: '',
      sval: this.$route.params.conditionVal,
      list: [],
      loading: false,
      finished: false,
      isLoading: false,
      startline: 1,
      rebackobject: { reBackflag: false },
      fieldref: this.$route.params.fieldref,
      selecteddata: [],
      listMode: 'tree'

    }
  },
  watch: {
    selecteddata: {
      handler(val) {
        if (this.mode === 'single') {

          this.handleChecked(val[0])

          // const item = val[0]
          // const storeObj = {
          //   ref_id: item.id,
          //   ref_show: item?.extra?.sname || '',
          //   ref_field: this.$route.params.field
          // }

          // this.$store.commit('refReBack', storeObj)
          // // Toast('已选中')
          // setTimeout(() => {
          //   this.$router.go(-1)
          // }, 200)
        }
      },
      deep: true
    }

  },
  mounted() {
    this.onLoad()
  },
  methods: {
    handleExpand(item, isShow) {

      if (!isShow) {
        item.extra.show = isShow
        return
      }

      let data = {
        'ref_object': this.$route.params.bo,
        'ref_toobject': this.$route.params.tobo,
        'ref_tofieldas': this.$route.params.field,
        'ref_inview': this.$route.params.conditionValHidden,
        // 'ref_inview': '',
        'view_page': this.startline,
        'view_rownum': `10000`,
        'view_id': this.$route.params.viewid,
        'ref_classname': this.$route.params.classname,
        'ref_params': this.$route.params.params,
        'ref_conditionval': this.keyword,
        ref_depid: item.id, // 部门id，默认所有
        conf_searchall: false  //查询全部，默认false
      }

      data.ref_inview = data.ref_inview.replace(':in:', ':in:' + this.sval)
      //console.log('data.ref_inview', data.ref_inview)
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      this.axios({
        method: 'post',
        url: '/api/ref.listnew.do',
        data: qs.stringify(data)
      }).then(res => {
        //console.log(res)
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          } else {
            this.$router.go(-1)
          }
        } else {
          item.extra.show = isShow
          this.$set(item, "children", res.data.jsondata.outdata)
          // item.children = res.data.jsondata.outdata
        }
      }).catch(res => {
        this.reserror(res)
      }).finally(() => {
        Toast.clear()
      })

    },
    
    async handleChecked(item, isChecked) {
 
      if (this.mode === 'single') {

        
        const res = await this.getRefSelect(item.id)

        const storeRefObj = {
          ref_id: item.id,
          ref_show: item?.extra?.sname || '',
          ref_field: this.$route.params.field,
          ref_item: item
        }
        const outdata = res.data.jsondata.outdata
        if (Object.getOwnPropertyNames(outdata).length > 2) {
          storeRefObj.ref_map = outdata
          storeRefObj.ref_toobject = this.$route.params.tobo
        }
        this.$store.commit('refReBack', storeRefObj)
        this.$router.go(-1)






        return

        const storeObj = {
          ref_id: item.id,
          ref_show: item?.extra?.sname || '',
          ref_field: this.$route.params.field
        }
        item.extra.checked = isChecked
        this.$store.commit('refReBack', storeObj)
        this.$router.go(-1)
      }
    },
    async reBack() {
      let refid = ''
      let refval = ''

      // blfx单独处理
      // if (this.$route.params.tobo == 'bflxmx' || this.$route.params.tobo === 'jhglmx') {
      //   let refArr = this.selecteddata
      //   //console.log('refArr', refArr)
      //   let payload = { ref_arr: refArr }
      //   this.$store.commit('refReBack', payload)
      //   this.$router.go(-1)
      //   return
      // }
      for (let i = 0; i < this.selecteddata.length; i++) {
        refid += this.selecteddata[i].id + ';'
        refval += this.selecteddata[i].extra[this.$route.params.fieldref] + ';'
      }


      // 回写
      // this.$toast(item.id + '-->' + item.title)
      let payload = { ref_id: refid, ref_show: refval, ref_field: this.$route.params.field, ref_item: this.selecteddata[0] }
      //console.log('payload', payload)
      this.$store.commit('refReBack', payload)
      this.$router.go(-1)
    },
    getRefSelect(id) {
      const data = {
        ref_object: this.$route.params.bo,
        ref_id: id,
        ref_toobject: this.$route.params.tobo,
        ref_tofieldas: this.$route.params.field,
        ref_tofield: this.$route.params.field,
        ref_classname: this.$route.params.classname,
        ref_params: this.$route.params.params
      }
      return this.axios({
        method: 'post',
        url: '/api/ref.select.do',
        data: qs.stringify(data)
      })
    },

    onLoad() {
      let data = {
        'ref_object': this.$route.params.bo,
        'ref_toobject': this.$route.params.tobo,
        'ref_tofieldas': this.$route.params.field,
        'ref_inview': this.$route.params.conditionValHidden,
        'view_page': this.startline,
        'view_rownum': `10000`,
        'view_id': this.$route.params.viewid,
        'ref_classname': this.$route.params.classname,
        'ref_params': this.$route.params.params,
        'ref_conditionval': this.keyword,
        ref_depid: '', // 部门id，默认所有
        conf_searchall: false  //查询全部，默认false
      }

      data.ref_inview = data.ref_inview.replace(':in:', ':in:' + this.sval)
      //console.log('data.ref_inview', data.ref_inview)
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
      this.axios({
        method: 'post',
        url: '/api/ref.listnew.do',
        data: qs.stringify(data)
      }).then(res => {
        //console.log(res)
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          } else {
            this.$router.go(-1)
          }
        } else {
          this.orgData = res.data.jsondata.outdata
        }
      }).catch(res => {
        this.reserror(res)
      }).finally(() => {
        Toast.clear()
      })
    },
    onRefresh() {
      this.list = []
      this.startline = 1
      this.isLoading = false
      this.loading = true
      this.finished = false
      this.onLoad()
    },

    openNew() {
      this.$router.push({ name: 'new', query: { idobject: this.$route.params.bo, newflag: 'refnew', reBackflag: this.rebackobject } })
    },

    onSearch() {
      if (this.keyword === '') {
        this.listMode = 'tree'
      } else {
        this.listMode = 'list'
      }
      this.onLoad()
    },
    onCancel() {
      this.sval = ''
      this.list = []
      this.startline = 1
      // this.onLoad()
      this.$router.go(-1)
    }
    // reBack(item) {
    //   // 回写
    //   // this.$toast(item.id + '-->' + item.title)
    //   //console.log('refBack: ', item.id, this.fieldref, item[this.fieldref], this.$route.params.field, item)
    //   this.$store.commit('refReBack', { ref_id: item.id, ref_show: item[this.fieldref], ref_field: this.$route.params.field, ref_item: item })
    //   this.$router.go(-1)
    // }
  },
  activated() {
    if (this.$store.state.ref_show === 'true') {
      this.$store.state.ref_show = ''
      this.$store.state.ref_id = ''
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
.L-orgRef {
  position: relative;
}

.L-orgTree {
  padding: 5px 8px;
  box-sizing: border-box;
  margin-bottom: 40px;
  margin-top: 50px;
}

.L-top-bar {
  position: fixed;
  width: 100%;
  height: 55px;
  border-bottom: 1px solid #f0f0f0;
  top: 0;
  left: 0;

}

.L-orgRef-tabbar {
  text-align: center;
  width: 100%;
  box-sizing: border-box;
  padding-top: 3px;
}
</style>
